package net.starwifi.duobao.service.impl;

import com.google.common.collect.Maps;
import net.starwifi.duobao.entity.GglWinning;
import net.starwifi.duobao.mvc.Page;
import net.starwifi.duobao.mvc.PageView;
import net.starwifi.duobao.repository.GglWinningRepository;
import net.starwifi.duobao.service.BaseServiceImpl;
import net.starwifi.duobao.service.GglWinningService;
import net.starwifi.duobao.utils.CompressUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Service
public class GglWinningServiceImpl extends BaseServiceImpl<GglWinning,Long> implements GglWinningService {

    @Autowired
    GglWinningRepository gglWinningRepository;
    @Override
    public int OnStatus(Long id,int status){
        return gglWinningRepository.OnStatus(id,status);
    }

    /**
     * 导出文件的最大大小 超过这个大小会压缩
     */
    private final int MAX_EXPORT_FILE_SIZE = 10 * 1024 * 1024; //10MB
    private final String storePath = "upload/excel";
    private final String EXPORT_FILENAME_PREFIX = "excel";

    @Override
    public String exportExcel2003WithUsermodel(String basePath, String contextRootPath, PageView pageView) {

        int perSheetRows = 60000; //每个sheet 6w条
        int totalRows = 0;
//        Long maxId = 0L;
        String resultURL="";
        String fileName = generateFilename(basePath, contextRootPath, "xls");
        File file = new File(fileName);
        BufferedOutputStream out = null;
        try {
            long beginTime = System.currentTimeMillis();

            HSSFWorkbook wb = new HSSFWorkbook();
            Sheet sheet = wb.createSheet();
            Row headerRow = sheet.createRow(0);

            Cell cell = headerRow.createCell(0);
            cell.setCellValue("用户ID");
            cell = headerRow.createCell(1);
            cell.setCellValue("用户名");
            cell = headerRow.createCell(2);
            cell.setCellValue("参与活动");
            cell = headerRow.createCell(3);
            cell.setCellValue("等奖");
            cell = headerRow.createCell(4);
            cell.setCellValue("奖品");
            cell = headerRow.createCell(5);
            cell.setCellValue("是否兑换");
            cell = headerRow.createCell(6);
            cell.setCellValue("中奖时间");


            totalRows = 1;
            double sumFee=0;

            pageView.setNumPerPage(200); //每次查询200行
            Long total=getMQueryCount(pageView.getFilters()); //记录总数
            int totalPage=(int) Math.ceil((double) total / (double) 200); //总页数
            int num=0;//序号
            try {
                for(int i=1;i<=totalPage;i++){
                    pageView.setPageNumber(i); //当前页
                    Page<GglWinning> page = getScrollData(pageView);
                    DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                    for (GglWinning data : page.getContent()) {
                        Row row = sheet.createRow(totalRows);

                        Cell datacell = row.createCell(0);
                        datacell.setCellValue(data.getMemberId());
                        datacell = row.createCell(1);
                        datacell.setCellValue(data.getMobile());
//                        String memberType="";
//                        if(data.getMemberType()==0){
//                            memberType="普通用户";
//                        }else {
//                            memberType="商家用户";
//                        }
                        datacell = row.createCell(2);
                        datacell.setCellValue(data.getGglhdname());
                        datacell = row.createCell(3);
                        datacell.setCellValue(data.getJpname());
                        datacell = row.createCell(4);
                        datacell.setCellValue(data.getJp());

                        String status="";
                        if(data.getStatus()==1){
                            status="已兑换";
                        }else {
                            status="未兑换";
                        }
                        datacell = row.createCell(5);
                        datacell.setCellValue(status);
                        datacell = row.createCell(6);
                        datacell.setCellValue(format.format(data.getWinningDate()));

                        totalRows++;
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            clear();
            out = new BufferedOutputStream(new FileOutputStream(file));
            wb.write(out);
            IOUtils.closeQuietly(out);
            if(needCompress(file)) {
                fileName = compressAndDeleteOriginal(fileName);
            }
            long endTime = System.currentTimeMillis();

            Map<String, Object> context = Maps.newHashMap();
            context.put("seconds", (endTime - beginTime) / 1000);
            context.put("url", fileName.replace(contextRootPath, ""));
            resultURL=fileName.replace(contextRootPath, "");
        } catch (Exception e) {
            IOUtils.closeQuietly(out);
            Map<String, Object> context = Maps.newHashMap();
            context.put("error", e.getMessage());
        }
        return resultURL;
    }

    private String compressAndDeleteOriginal(final String filename) {
        String newFileName = FilenameUtils.removeExtension(filename) + ".zip";
        compressAndDeleteOriginal(newFileName, filename);
        return newFileName;
    }

    private void compressAndDeleteOriginal(final String newFileName, final String... needCompressFilenames) {
        CompressUtils.zip(newFileName, needCompressFilenames);
        for(String needCompressFilename : needCompressFilenames) {
            FileUtils.deleteQuietly(new File(needCompressFilename));
        }
    }

    /**
     * 生成要导出的文件名
     * @param basePath
     * @param contextRootPath
     * @param extension
     * @return
     */
    private String generateFilename(final String basePath, final String contextRootPath, final String extension) {
        return generateFilename(basePath, contextRootPath, null, extension);
    }
    private String generateFilename(final String basePath, final String contextRootPath, Integer index, final String extension) {
        String path = FilenameUtils.concat(contextRootPath, storePath);
        path = FilenameUtils.concat(path, basePath);
        path = FilenameUtils.concat(
                path,
                EXPORT_FILENAME_PREFIX + "_" +
                        DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS") +
                        (index != null ? ("_" + index) : "") +
                        "." + extension);

        File file = new File(path);
        if(!file.exists()) {
            File parentFile = file.getParentFile();
            if(!parentFile.exists()) {
                parentFile.mkdirs();
            }
            return path;
        }
        return generateFilename(basePath, contextRootPath, extension);
    }


    private boolean needCompress(final File file) {
        return file.length() > MAX_EXPORT_FILE_SIZE;
    }


}
